<?php
namespace app\common\service;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Config;

class AliSmsService
{
    protected $config;

    public function __construct()
    {
        $this->config = Config::get('alisms');
        AlibabaCloud::accessKeyClient(
            $this->config['access_key_id'],
            $this->config['access_key_secret']
        )->asDefaultClient();
    }

    /**
     * 发送短信
     * @param string $phoneNumbers 手机号
     * @param array $params 短信参数
     * @return mixed
     */
    public function sendSms($phoneNumbers, $params)
    {

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->RegionId("cn-hangzhou")
                ->options([
                    'query' => [
                        'PhoneNumbers' => $phoneNumbers,
                        'SignName' => $this->config['sign_name'],
                        'TemplateCode' => $this->config['template_code'],
                        'TemplateParam' => json_encode($params),
                    ],
                ])
                ->request();

            return $result->toArray();
        } catch (ClientException $e) {
            throw new \Exception("CLIENT_ERROR: {$e->getMessage()}");
        } catch (ServerException $e) {
            throw new \Exception("SERVER_ERROR: {$e->getMessage()}");
        } catch (\Exception $e) {
            throw new \Exception("UNEXPECTED_ERROR: {$e->getMessage()}");
        }
    }
}